package com.zhouxiaoge.dao;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Repository;

import java.util.List;

/**
 * @author 周明阳
 * mail:gqzmy@outlook.com
 * 时间:2018-04-23 15:25
 */
@Repository
public class UserRunAsDaoImpl implements UserRunAsDao {
    @Autowired
    private JdbcTemplate jdbcTemplate;

    @Override
    public void grantRunAs(Long fromUserId, Long toUserId) {
        String sql = "INSERT INTO sys_user_runas(from_user_id, to_user_id) VALUES (?,?)";
        if (!exists(fromUserId, toUserId)) {
            jdbcTemplate.update(sql, fromUserId, toUserId);
        }
    }

    public boolean exists(Long fromUserId, Long toUserId) {
        String sql = "SELECT COUNT(1) FROM sys_user_runas WHERE from_user_id=? AND to_user_id=?";
        return jdbcTemplate.queryForObject(sql, Integer.class, fromUserId, toUserId) != 0;
    }

    @Override
    public void revokeRunAs(Long fromUserId, Long toUserId) {
        String sql = "DELETE FROM sys_user_runas WHERE from_user_id=? AND to_user_id=?";
        jdbcTemplate.update(sql, fromUserId, toUserId);
    }

    @Override
    public List<Long> findFromUserIds(Long toUserId) {
        String sql = "SELECT from_user_id FROM sys_user_runas WHERE to_user_id=?";
        return jdbcTemplate.queryForList(sql, Long.class, toUserId);
    }

    @Override
    public List<Long> findToUserIds(Long fromUserId) {
        String sql = "SELECT to_user_id FROM sys_user_runas WHERE from_user_id=?";
        return jdbcTemplate.queryForList(sql, Long.class, fromUserId);
    }
}
